import { Form, Input , Select , DatePicker, Flex , Button , Space, Table , Dropdown , Tabs, Modal, message, Progress } from 'antd';
import type { TableProps , TabsProps } from 'antd';
import style from '../css/Registrationinquiry.module.scss'
import { SearchOutlined , UploadOutlined , PlusCircleOutlined , DownOutlined} from '@ant-design/icons';
import { useEffect, useRef, useState } from 'react';
import { registerlistcan, registerlistsel, registerliststa } from '../utils/request';
import moment from 'moment';
import Padination from '../components/Pagination';
import { useNavigate } from 'react-router';
import { exportDataToExcel } from '../components/exportToExcel'
function Registrationinquiry() {
    const [form] = Form.useForm();
    const [formOne] = Form.useForm();
    const { RangePicker } = DatePicker;
    const usenavgia = useNavigate()
    // 搜索盒子展开与收回
    const [withdraw, setWithdraw] = useState(true)
    const expand = () => {
        if (withdraw) {
            console.log('收回')
        } else {
            console.log('展开')
        }
        setWithdraw(!withdraw)
    }
    

    const labels: TabsProps['items'] = [
        {
            key: '1',
            label: '全部挂号',
        },
        {
            key: '2',
            label: '待就诊',
        },
        {
            key: '3',
            label: '已就诊',
        },
        {
            key: '4',
            label: '已退号',
        },
        {
            key: '5',
            label: '已失效',
        },
    ];
    // 标签页
    const onChange = (key: string) => {
        console.log(labels[Number(key)-1].label);
        if(Number(key)-1){
            registerliststa({
                status:labels[Number(key)-1].label
            }).then(res=>{
                console.log(res.data)
                setMockData(res.data)
                setData(res.data.slice(0,10))
            }).catch(err=>{
                console.log(err)
            })
        }else{
            registerlistsel().then(res=>{
                console.log(res.data)
                setMockData(res.data)
                setData(res.data.slice(0,10))
            }).catch(err=>{
                console.log(err)
            })
        }
        
    };

    // 表格数据
    interface DataType {
        register_id: Number;
        Medicalnumber: string,
        PatientIDCard: string,
        name: string,
        department: string,
        doctor: string,
        amountmoney: string,
        status: string,
        date: string,
        timestamp: string
    }

    const columns: TableProps<DataType>['columns'] = [
        {
            title: '病历号',
            dataIndex: 'Medicalrecord',
            key: 'Medicalrecord',
            width: 118
        },
        {
            title: '就诊卡号',
            dataIndex: 'Medicalcard',
            key: 'Medicalcard',
            width: 119
        },
        {
            title: '患者姓名',
            dataIndex: 'name',
            key: 'name',
            width: 109
        },
        {
            title: '挂号科室',
            key: 'department',
            dataIndex: 'department',
            width: 127
        },
        {
            title: '挂号医生',
            dataIndex: 'doctor',
            key: 'doctor',
            width: 107,
            render:(text)=><span style={{overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{text}</span>
        },
        {
            title: '挂号金额',
            dataIndex: 'money',
            key: 'money',
            width: 104,
            render:(text)=><span>{'￥'+text.toFixed(2)}</span>
        },
        {
            title: '挂号状态',
            dataIndex: 'status',
            key: 'status',
            width: 89,
            render: (text) => (
                <div style={{
                    display: 'flex',
                    alignItems: 'center'
                }}>
                    <p className={text == '待就诊' ? style.bluestatus : text == '已就诊' ? style.greenstatus : text == '已退号' ? style.orengestatus : style.graystatus} style={{
                        width: 8,
                        height: 8,
                        borderRadius: '50%',
                        marginRight: 5
                    }}></p>
                    <span>{text}</span>
                </div>
            )
        },
        {
            title: '挂号日期',
            dataIndex: 'date',
            key: 'date',
            width: 210
        },
        {
            title: '挂号时间',
            dataIndex: 'timestamp',
            key: 'timestamp',
            width: 182,
            render:(text) =><span>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</span>,
        },
        {
            title: '操作',
            key: 'operation',
            width: 210,
            fixed: 'right',
            render: (_, { status , register_id}) => (
                <Space size="small">
                    <a onClick={()=>details(register_id)}>详情</a>
                    <a className={status == '待就诊' ? style.show : style.hidden} onClick={()=>cannel(register_id)}>取消挂号</a>
                    <Dropdown  menu={{ items }} className={status == '已退号' ? style.hidden : status == '已失效' ? style.hidden : style.show}>
                        <a>
                            更多 <DownOutlined />
                        </a>
                    </Dropdown>
                </Space>
            ),
        },
    ];
    //   更多
    const items = [
        { key: '1', label: '打印发票' ,onClick(){invoice()}},
        { key: '2', label: '打印小票' ,onClick(){receipt()}},
    ];
    // 页面初始获取
    const [mockData,setMockData] = useState([])
    useEffect(()=>{
        registerlistsel().then(res=>{
            console.log(res.data)
            setMockData(res.data)
            setData(res.data.slice(0,10))
        }).catch(err=>{
            console.log(err)
        })
    },[])
    const [data,setData] = useState<DataType[]>([])
    // 分页传递数据 
    const getshowsize=(data: any)=>{
        setData(mockData.slice((data.current-1)*data.pageSize,data.pageSize*data.current))
    }
   
    // 搜索
    const [loading,setLoading] = useState(false)
    const Search=()=>{
        console.log('搜索')
        setLoading(true)
        setTimeout(() => {
            setLoading(false)
            console.log('添加name属性')
            form.validateFields().then(values => {
                console.log('Validated values: ', values);
            }).catch(info => {
                console.log('Validate Failed:', info);
            });
        }, 2000);
    }
    // 重置
    const reset=()=>{
        console.log('重置')
        form.resetFields();
    }
    // 导出
    const exports=()=>{
        console.log('导出')
        exportDataToExcel(data,'data.xlsx')
    }
    // 新增挂号
    const insert=()=>{
        console.log('新增挂号,去门诊挂号页面')
        usenavgia('/index/Registrationmanagement/Outpatientregistration')
    }
    // 详情
    const details=(i: Number)=>{
        console.log('详情,去挂号详情页面',i)
        usenavgia('/index/Registrationmanagement/Registrationinquiry/Registerdetails?id='+i)
    }
    // 取消
    const [cancliID,setCancelID] = useState<Number>(0)
    const cannel=(i: Number)=>{
        console.log('取消挂号')
        setCancelID(i)
        setIsDeleteModalVisible(true)
    }
    // 快捷语   
    const [qukilyact,setQukilyact] = useState(0)
    const [qukily] = useState(['不想挂号了', '挂错号了', '其他'])
    const [textarea, setTextarea] = useState('')
    const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);
    const [registerloading, setregisterLoading] = useState(false);
    const settextarea = (i: number) => {
        setTextarea(qukily[i])
        setQukilyact(i)
        console.log(qukily[i])
    }
    const handleOk = () => {
        // console.log('确认')
        formOne.validateFields().then(values => {
            console.log('Validated values: ', values);
            setregisterLoading(true)
            setTimeout(() => {
                registerlistcan({
                    id:cancliID,
                    status:'已退号'
                }).then(res=>{
                    setMockData(res.data)
                    setData(res.data.slice(0,10))
                }).catch(err=>{
                    console.log(err)
                })
                setregisterLoading(false)
                setIsDeleteModalVisible(false)
                formOne.resetFields()
                message.success(`注销操作成功！`);
            }, 2000);
        }).catch(info => {
            console.log('Validate Failed:', info);
        });
    };

    const handleCancel = () => {
        console.log('取消')
        setIsDeleteModalVisible(false)
        formOne.resetFields()
        message.warning('已取消操作')
    };
    // 打印发票
    const invoice=()=>{
        console.log('打印发票')
    }
    // 打印小票
    const [Printreceipts, setPrintreceipts] = useState(false)
    const [percent, setPercent] = useState<number>(0);
    const intervalRef = useRef<number | null>(null);
    const [printlod, setPrintlod] = useState(false)
    const [printtext, setPrinttext] = useState('打印')
    const [close, setClose] = useState(false)
    const [printcount, setCount] = useState<number>(0);
    // 清除进度条定时器
    const clearIntervalIfSet = () => {
        if (intervalRef.current) {
            clearInterval(intervalRef.current);
            intervalRef.current = null;
        }
    };
    const receipt = () => {
        console.log('打印小票')
        setPrintreceipts(true)
    }
    const printOK = () => {
        setPrintlod(true)
        setPrinttext('打印中')
        clearIntervalIfSet(); // 确保没有重复的定时器
        let currentPercent = 0;
        intervalRef.current = setInterval(() => {
            if (currentPercent < 100) {
                currentPercent += 1; // 你可以调整这个值来改变进度条的速度
                setPercent(currentPercent);
            } else {
                clearIntervalIfSet();
                setPrintlod(false)
                setClose(true)
                setCount(prevCount => prevCount + 1); // 使用函数式更新来确保获取最新的count值
            }
        }, 100); // 你可以调整这个值来改变进度条更新的频率
    }
    const PrintCancel = () => {
        setPrintreceipts(false)
        setPercent(0)
        setClose(false)
        setPrinttext('打印')
    }
    // 组件卸载时清除定时器
    useEffect(() => {
        return () => clearIntervalIfSet();
    }, []);
    return ( 
        <>
            {/* 取消挂号 */}
            <Modal
                onOk={handleOk}
                onCancel={handleCancel}
                title={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E8%AE%BE%E8%AE%A1%E7%BB%84%E4%BB%B6/u268.svg" alt="" />
                        <span style={{ marginLeft: 5 }}>确认取消</span>
                    </div>
                }
                open={isDeleteModalVisible}
                footer={[
                    <Flex key='flex' justify='flex-end'>
                        <Button key="back" onClick={handleCancel} style={{ height: 32, marginRight: 10 }}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={registerloading} onClick={handleOk} style={{ height: 32 }}>
                            确认
                        </Button>,
                    </Flex>
                ]}
                width={375}
            >
                <Form
                    form={formOne}
                    style={{
                        marginTop: 20
                    }}
                    initialValues={{ note: textarea }}
                >
                    <Form.Item className={style.itemstyle} name='note'>
                        <Input.TextArea placeholder='请输入挂号取消原因' style={{ height: 80, borderRadius: 0, resize: 'none', margin: 'auto' }} rows={4} />
                    </Form.Item>
                </Form>
                <div className={style.Quicklanguage}>
                    <p>快捷备注语：</p>
                    <ul>
                        {
                            qukily.map((item,index) =>
                                <li key={item} className={qukilyact==index?style.active:''} onClick={() => settextarea(index)}>{item}</li>
                            )
                        }
                    </ul>
                </div>
            </Modal>
            {/* 打印小票 */}
            <Modal
                onOk={printOK}
                onCancel={PrintCancel}
                title={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E8%AE%BE%E8%AE%A1%E7%BB%84%E4%BB%B6/u268.svg" alt="" />
                        <span style={{ marginLeft: 5 }}>打印小票</span>
                    </div>
                }
                open={Printreceipts}
                footer={[
                    <Flex key='flex' justify='space-between' align='center'>
                        <Button className={close?style.close:''} key="submit" type="primary" loading={printlod} onClick={printOK} style={{ height: 32 }}>
                            {printtext}
                        </Button>
                        <Button onClick={PrintCancel} className={close?'':style.close}>关闭</Button>
                        <p>已打印<span style={{color:'#0468ff'}}>{printcount}</span>次</p>
                    </Flex>
                ]}
                width={375}
            >
                <Progress strokeColor='#0468ff' percent={percent} />
            </Modal>
            {/* 页面搜索盒子 */}
            <div className={style.searchboxs}>
                <Form
                    form={form}
                    className={style.formbox}
                >
                    <Form.Item label="就诊卡号" name='PatientCard' colon={false} className={style.itemstyle}>
                        <Input style={{
                            width:200,
                            height:32
                        }}
                        placeholder='请输入'
                        ></Input>
                    </Form.Item>
                    <Form.Item label="患者姓名" name='name' colon={false} className={style.itemstyle}>
                        <Input style={{
                            width:200,
                            height:32
                        }}
                        placeholder='请输入'
                        ></Input>
                    </Form.Item>
                    <Form.Item label="证件号" name='IDcard' colon={false} className={style.itemstyle}>
                        <Input style={{
                            width:200,
                            height:32
                        }}
                        placeholder='请输入'
                        ></Input>
                    </Form.Item>
                    <Flex className={withdraw?'':style.hidden}>
                        <Form.Item label="就诊号" name='Medicalnumber' colon={false} className={style.itemstyle}>
                            <Input style={{
                                width:200,
                                height:32
                            }}
                            placeholder='请输入'
                            ></Input>
                        </Form.Item>
                        <Form.Item label="挂号状态" name='status' rules={[{
                                required:false
                            }]} className={style.itemstyle} colon={false}>
                            <Select
                                allowClear 
                                placeholder='请选择'
                                style={{ width: 200 , height:32 }}
                                options={[
                                    { value: '全部状态', label: '全部状态' },
                                    { value: '待就诊', label: '待就诊' },
                                    { value: '已就诊', label: '已就诊'},
                                    { value: '已退号', label: '已退号'},
                                    { value: '已失效', label: '已失效'},
                                ]}
                                />
                        </Form.Item>
                        <Form.Item label="挂号时间" name='time' className={style.itemstyle} colon={false}> 
                            <RangePicker style={{
                                width:305,
                                height:32
                            }} />
                        </Form.Item>
                    </Flex>
                    <Flex justify='space-between' style={{
                        width:'100%'
                    }}>
                        <Flex>
                            <Form.Item label="挂号医生" name='doctor' colon={false} className={style.itemstyle}>
                                <Input style={{
                                    width:200,
                                    height:32
                                }}
                                placeholder='请输入'
                                ></Input>
                            </Form.Item>
                            <Form.Item label="挂号科室"  name='depart' colon={false} className={style.itemstyle} >
                                <Input style={{
                                    width:200,
                                    height:32
                                }}
                               
                                placeholder='请输入'
                                ></Input>
                            </Form.Item>
                        </Flex>
                        <Flex align='center' justify='space-between' style={{width:250}}>
                            <div>
                                <Button style={{
                                    marginRight:10
                                }} onClick={()=>reset()}>重置</Button>
                                <Button type="primary" onClick={()=>Search()} loading={loading} icon={<SearchOutlined />}>
                                    搜索
                                </Button>
                            </div>
                            <p style={{
                                width:50,
                                cursor:'pointer'
                            }}
                                onClick={()=>expand()}
                            >
                                <span style={{color:'#0468ff',marginRight:5}}>{withdraw?'收起':'展开'}</span>
                                <img style={withdraw?{transform:'rotate(180deg)'}:{}} src="https://cdn7.axureshop.com/demo2024/2321849/images/%E6%8C%82%E5%8F%B7%E6%9F%A5%E8%AF%A2/u4306.svg" alt="" />
                            </p>
                        </Flex>
                    </Flex>
                </Form>
            </div>
            <div className={style.tablebox}>
                <div className={style.tabletitle}>
                    <Tabs className={style.tags} defaultActiveKey="1" items={labels} onChange={onChange} />
                    <ul className={style.statistics}>
                        <li>
                            挂号总数：
                            <span style={{color:'#0468ff'}}>50个</span>
                        </li>
                        <li>
                            挂号总金额：
                            <span style={{color:'#0468ff'}}>￥6500.00</span>
                        </li>
                        <li>
                            退号数：
                            <span style={{color:'#FA6A1C'}}>10个</span>
                        </li>
                        <li>
                            退号金额：
                            <span style={{color:'#FA6A1C'}}>￥500</span>
                        </li>
                    </ul>
                </div>
                <div className={style.datalists}>
                    <div className={style.buttonbox}>
                        <Button type="primary" onClick={()=>exports()} style={{color:'#0460ff',width:75,height:32,borderRadius:0,marginRight:10}} ghost icon={<UploadOutlined />}>
                            导出
                        </Button>
                        <Button type="primary" style={{width:103,height:32,borderRadius:0}} onClick={()=>insert()} icon={<PlusCircleOutlined />}>
                            新增挂号
                        </Button>
                    </div>
                    <Table<DataType> columns={columns} dataSource={data} className={style.custom_table} rowKey='register_id' scroll={{ x: 'max-content' }} pagination={false}/>
                    {/* 分页器 */}
                    <Padination total={mockData.length} showsize={getshowsize}></Padination>
                </div>
            </div>
        </>
     );
}

export default Registrationinquiry;